package com.dagene.weixin.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import com.dagene.weixin.bean.Article;
import com.dagene.weixin.bean.NewsMessage;

public class Util {
	public static void main(String[] args) {
		getWeather("杭州", null);
	}

	static long lasttimeAccessToken = 0l;
	static String accessToken = null;

	public static String getAccessToken() {
		if (System.currentTimeMillis() - lasttimeAccessToken > 7000000
				|| accessToken == null) {
			// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
			String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
					+ Constants.APPID + "&secret=" + Constants.APPSECRET;
			JSONObject jsonObj = getJSONObjectByGet(accessTokenUrl);
			lasttimeAccessToken = System.currentTimeMillis();
			if (jsonObj.has("access_token")) {
				accessToken = jsonObj.get("access_token").toString();
				return accessToken;
			}
			return accessToken;
		} else {
			return accessToken;
		}
		// access_token
	}

	public static String getAccessTokenByForce(boolean force) {
		if (!force)
			return getAccessToken();
		// if (System.currentTimeMillis()-lasttimeAccessToken>7000000 ||
		// accessToken==null) {
		// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
		String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
				+ Constants.APPID + "&secret=" + Constants.APPSECRET;
		JSONObject jsonObj = getJSONObjectByGet(accessTokenUrl);
		lasttimeAccessToken = System.currentTimeMillis();
		if (jsonObj.has("access_token")) {
			accessToken = jsonObj.get("access_token").toString();
			return accessToken;
		}
		return accessToken;

		// access_token
	}

	private static HttpClient getHttpClient() {
		HttpClient httpClient = HttpClientBuilder.create().build();
		return httpClient;
	}

	public static JSONObject getJSONObjectByGet(String requestUrl) {
		BufferedReader bufferedReader = null;
		HttpResponse httpResponse = null;
		JSONObject resultJsonObject = null;
		try {
			// HttpClient发出一个HttpGet请求
			HttpClient httpClient = getHttpClient();
			httpResponse = httpClient.execute(new HttpGet(requestUrl));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 得到httpResponse的状态响应码
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK) {
			// 得到httpResponse的实体数据
			HttpEntity httpEntity = httpResponse.getEntity();
			StringBuilder entityStringBuilder = new StringBuilder();
			if (httpEntity != null) {
				try {
					bufferedReader = new BufferedReader(new InputStreamReader(
							httpEntity.getContent(), "UTF-8"), 8 * 1024);
					String line = null;
					while ((line = bufferedReader.readLine()) != null) {
						entityStringBuilder.append(line);
					}
					// 利用从HttpEntity中得到的String生成JsonObject
					resultJsonObject = JSONObject
							.fromObject(entityStringBuilder.toString());
					// resultJsonObject= new
					// JSONParser().parse(entityStringBuilder.toString());

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return resultJsonObject;

	}

	public static void getWeather(String cityName, NewsMessage newsMessage) {
		// http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=杭州
		System.out.println("getWeather:" + cityName);
		String url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName="
				+ cityName;
		HttpUtil httpUtil = new HttpUtil();
		List<String> strs = new ArrayList<String>();// httpUtil.httpRequestNoSsl(url,
													// "GET", null);
		strs.add("杭州");
		strs.add("0℃/11℃");
		strs.add("1月16日晴");
		strs.add("东风微风");
		strs.add("1.gif");
		strs.add("今日天气实况：气温：9℃；风向/风力：南风 2级；湿度：47%；空气质量：暂无；紫外线强度：中等");
		List<Article> articleList = new ArrayList<Article>();
		if (strs != null && strs.size() >= 5) {
			System.out.println(strs.get(0)
					+ "http://weixin.dazd.cn/weatherimages/" + strs.get(4));
			Article article1 = new Article();
			article1.setTitle(strs.get(0) + strs.get(2) + strs.get(1));
			// article1.setDescription(strs.get(3) + strs.get(5));
			article1.setPicUrl("http://avatar.csdn.net/1/4/A/1_lyq8479.jpg");
			// article1.setUrl("http://blog.csdn.net/lyq8479/article/details/9157455");

			Article article2 = new Article();
			article2.setTitle(strs.get(5));
			article2.setDescription("");
			article2.setPicUrl("http://weixin.dazd.cn/weatherimages/a_1.jpg");
			article1.setUrl("http://weixin.dazd.cn/weatherimages/a_1.jpg");
			articleList.add(article1);
			articleList.add(article2);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
		}
	}

	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 *            字符串
	 * @return true/false
	 */
	public static boolean isNumeric(String str)

	{
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 判断字符串是否是手机号
	 * 
	 * @param phone
	 *            手机号
	 * @return true/false
	 */
	public static boolean isPhone(String phone) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[5,7])|(17[0,6-8]))\\d{8}$");
		Matcher m = p.matcher(phone);

		return m.matches();
	}

	/**
	 * 判断字符串是否是邮箱格式
	 * 
	 * @param email
	 *            邮箱
	 * @return true/false
	 */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	public static String getFileName(FileItem item) {

		String fileName = item.getName();

		fileName = replace(fileName, "\\", "/");

		// 新命名
		fileName = makeFileName(fileName);
		// 追加扩展名
		fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

		return fileName;
	}

	public static String replace(String source, String oldString,
			String newString) {

		StringBuffer output = new StringBuffer();
		int lengthOfSource = source.length();

		int lengthOfOld = oldString.length();

		int posStart = 0;

		int pos;
		while ((pos = source.indexOf(oldString, posStart)) >= 0) {
			output.append(source.substring(posStart, pos));
			output.append(newString);
			posStart = pos + lengthOfOld;
		}

		if (posStart < lengthOfSource) {
			output.append(source.substring(posStart));
		}

		return output.toString();
	}

	public static String makeFileName(String filename) {

		// 为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
		// return UUID.randomUUID().toString() + "_" + filename;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

		String str = sdf.format(new Date());

		return str + "_" + filename;
	}

	public static String dateStrFormatYHD(String dateStr) throws Exception {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Date date = sdf.parse(dateStr);
		return sdf.format(date);

	}

	public static Date dateStrToDate(String dateStr) throws Exception {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		return sdf.parse(dateStr);

	}

	public static Date dateStrToNextDate(String dateStr) throws Exception {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Date ret = sdf.parse(dateStr);
		return new Date(ret.getTime() + 60 * 60 * 1000 * 24 - 1);
	}

	public static boolean isIPhone(HttpServletRequest request) {
		String ua = request.getHeader("User-Agent");
		if (ua != null) {
			if (ua.indexOf("iPhone") > -1 || ua.indexOf("iPad") > -1) {
				return true;
			}
		}
		return false;

	}

	/**
	 * 
	 * @param day
	 * @param num接下去几天
	 *            ，可为负数
	 * @return
	 */
	public static Date getNextDate(Date day, int num) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(day);
		cal.add(Calendar.DATE, num);
		return cal.getTime();
	}

	/**
	 * 过滤表情字符
	 * 
	 * @param str
	 * @return
	 */
	public static String filterExpression(String str) {
		String pattern = "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]";
		String reStr = "";
		Pattern emoji = Pattern.compile(pattern);
		Matcher emojiMatcher = emoji.matcher(str);
		return emojiMatcher.replaceAll(reStr);
	}

	/* 判断是否是数字 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
}
